/*
 * 作者: 侯晓宇
 * 时间: 2017-02-16
 * 说明：
 * Copyright (c) 2016-2017 中研沃兮
 */

define(function(require) {

	require("jquery");

	var c = require('app/utils/CommonUtils');
	var EventUtils = require('app/utils/EventUtils');
	var appInfo = require('app/AppInfo');
	var UserInfoUtils = require('app/utils/UserInfoUtils');
	var hc = require('app/utils/HttpClientUtils');
	var TimerUtils = require('app/utils/TimerUtils');
	var param = api.pageParam;
	var Scanfiles = api.require('Scanfiles');
	var dialog = new auiDialog({});
	var searching = false;
	var list = [];

	function startLoading() {
		$("#loading").css("width", "0");
		//10 000 秒
		//500
		var total = 20000;
		var target = 0.95;
		var i = 50;
		var current = 0;
		TimerUtils.startTimer(i, function() {

			current = current + i;
			var t = current / total * 100;

			if (t >= 100) {
				TimerUtils.stopTimer();
				return;
			}
			$("#loading").css("width", parseFloat(t * target) + "%");
		});

	}

	function stopLoading() {
		TimerUtils.stopTimer();
		$("#loading").css("width", "100%");

	}

	function filesSearching(startOrStop) {//start - true; stop - false;
		if (startOrStop) {//开始搜索
			searching = true;

			$("#tip").hide();
			$("#results").html("");

			$("#searchbtn").text("停止");
			$("#searchbtn").css("color", "#4a4a4a");

			startLoading();

		} else {//搜索结束
			searching = false;

			stopLoading();

			dialog.alert({
				title : "搜索结束",
				msg : '共找到' + list.length + '个您可能需要的文件',
				buttons : ['确定']
			}, function(ret) {

			})
			$("#searchbtn").text("搜索手机PPT，PDF文件");
			$("#searchbtn").css("color", "#ffffff");

		}

	}

	function splitFilePath(path) {
		var j = 0, k = 0;
		var len = path.length;
		j = path.lastIndexOf("/");
		k = path.lastIndexOf(".");
		var subs = path.substring(j + 1, k);
		var type = path.substring(k + 1, len);

		return {
			name : subs,
			type : type
		};
	}

	function renderFile(filepath) {
		list.push(filepath);
		var val = splitFilePath(filepath);
		var type = val.type;
		//pdf
		var name = val.name;

		var type_div = "pdf";
		if (type != "pdf") {
			type_div = "ppt";
		}

		var id = (new Date()).getTime() + "_upload";
		var item = $('<li data-path="' + filepath + '" class="aui-list-item" id="' + id + '" style="margin-bottom:0.5rem;">' + '<div class="aui-list-item-label-icon">' + '<img src="../image/' + type_div + '_icon.png" style="width:2rem;height:auto;">' + '</div>' + '<div class="aui-list-item-inner">' + name + '.' + type + '</div>' + '<div class="aui-label aui-label-info" style="line-height: 2rem;">点击上传</div>' + '</li>');

		$("#results").append(item);
		$("#" + id).click(function() {

			if (searching) {

				api.confirm({
					title : '温馨提示',
					msg : '是否停止搜索？'
				}, function(ret, err) {
					//coding...
					if (ret.buttonIndex == "2") {
						Scanfiles.stop();
					}	//coding...
				});
			} else {
				var path = $(this).data("path");
				hc.uploadPPT(path, null, 'ppt', function(resp) {
					if (resp.status != "201") {
						alert("上传失败，请重试");
					}

					var key = resp.result.key
					var ppturl = appInfo.pptserver + "/ppt_to_jpg";
					var callbackurl = appInfo.serverbase + "/luyan/pptcallback/userid/{0}/pptkey/{1}";
					callbackurl = callbackurl.replace("{0}", UserInfoUtils.getLoginedUser().userid);
					callbackurl = callbackurl.replace("{1}", key);

					var pptbody = {
						"key" : key,
						"callbackurl" : callbackurl,
						"pptname" : encodeURI(name),
						"type" : type
					};

					hc.post(ppturl, pptbody, function(resp) {

						if (c.l(resp.status) || resp.status == false) {
							dialog.alert({
								title : "上传失败",
								msg : '服务器正忙，请稍后再试',
								buttons : ['确定']
							}, function(ret) {
							});
							
						}else{
							dialog.alert({
								title : "上传成功",
								msg : '正在为您创建PPT语音直播间，可能需要几分钟时间，创建成功后会有短信提醒',
								buttons : ['确定']
							}, function(ret) {
								EventUtils.send('root', 'reset_me');
							});
						}
						
					});
				});

			}

		});

	}

	function scanfiles() {

		var types = ['ppt', 'pptx', 'pdf'];
		Scanfiles.scan({
			types : types
		}, function(ret) {

			//ret-> type, filepath, filepathlist, err
			if (ret.status) {
				//ret.type = start -> 表示开始搜索
				if (ret.type == "start") {
					console.log("start");
					filesSearching(true);
					list = [];
				}

				//ret.type = result -> 返回找到的最新的一条结果和所有结果的列表
				if (ret.type == "result") {
					console.log("result");
					console.log(ret.filepath);
					console.log(ret.filepathlist);
					renderFile(ret.filepath);
					// 返回所有找到的结果列表
				}

				//ret.type = end -> 表示结束搜索
				if (ret.type == "end") {
					console.log("end");
					console.log(ret.filepathlist);
					filesSearching(false);
				}

			} else {
				//ret.status为false，说明开始搜索失败，
				//				alert(JSON.stringify(ret.err));
				//ret.err为错误提示
			}
		});
	}

	function stopscan() {
		//搜索时间可能会很长，当找到要找当文件时，可以选择点击停止按钮，停止搜索。
		Scanfiles.stop();
	}


	$("#footer").click(function() {
		if (searching) {
			stopscan();
		} else {
			scanfiles();
		}
	});

	return;
});
